In [1]:
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split

# Set the path to the dataset
data_folder = "C:/yas_tahmini/UTKFaceee"

# Load and process the data
files = os.listdir(data_folder)
ages = []
genders = []
images = []

for file in files:
    parts = file.split('_')
    if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
        continue

    age, gender = map(int, parts[:2])
    full_path = os.path.join(data_folder, file)
    image = cv2.imread(full_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (224, 224))
    images.append(image)
    ages.append(age)
    genders.append(gender)

images_np = np.array(images) / 255
ages_np = np.array(ages)
genders_np = np.array(genders)

X_train, X_test, Y_age_train, Y_age_test, Y_gender_train, Y_gender_test = train_test_split(images_np, ages_np, genders_np, test_size=0.25)

# Load the pre-trained ResNet50 model
base_model = ResNet50(weights='imagenet', include_top=False)

# Age Model
x_age = GlobalAveragePooling2D()(base_model.output)
x_age = Dense(64, activation='relu')(x_age)
output_age = Dense(1, activation='relu', name='age_output')(x_age)
age_model = Model(inputs=base_model.input, outputs=output_age)
age_model.compile(optimizer=Adam(learning_rate=0.00005), loss='mae', metrics=['mae'])

# Gender Model
x_gender = GlobalAveragePooling2D()(base_model.output)
x_gender = Dense(64, activation='relu')(x_gender)
output_gender = Dense(1, activation='sigmoid', name='gender_output')(x_gender)
gender_model = Model(inputs=base_model.input, outputs=output_gender)
gender_model.compile(optimizer=Adam(learning_rate=0.00005), loss='binary_crossentropy', metrics=['accuracy'])

# Callbacks for Age Model
age_saver = ModelCheckpoint('age_model_weights.h5', monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True, mode='min')
age_early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='min')

# Callbacks for Gender Model
gender_saver = ModelCheckpoint('gender_model_weights.h5', monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=True, mode='min')
gender_early_stopping = EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='min')

# Train the Age Model
print("Training Age Model")
history_age = age_model.fit(
    X_train, Y_age_train,
    batch_size=32,
    validation_data=(X_test, Y_age_test),
    epochs=100,
    callbacks=[age_saver, age_early_stopping]
)

# Print the epoch number where Age Model training stopped
print(f"Age Model training stopped at epoch: {len(history_age.history['loss'])}")

# Train the Gender Model
print("Training Gender Model")
history_gender = gender_model.fit(
    X_train, Y_gender_train,
    batch_size=32,
    validation_data=(X_test, Y_gender_test),
    epochs=50,
    callbacks=[gender_saver, gender_early_stopping]
)

# Print the epoch number where Gender Model training stopped
print(f"Gender Model training stopped at epoch: {len(history_gender.history['loss'])}")

# Plotting the training and validation loss for Age Model
plt.figure(figsize=(12, 4))
plt.subplot(1, 2, 1)
plt.plot(history_age.history['loss'], label='Training Loss')
plt.plot(history_age.history['val_loss'], label='Validation Loss')
plt.title('Age Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

# Plotting the training and validation accuracy for Gender Model
plt.subplot(1, 2, 2)
plt.plot(history_gender.history['accuracy'], label='Training Accuracy')
plt.plot(history_gender.history['val_accuracy'], label='Validation Accuracy')
plt.title('Gender Model Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

plt.tight_layout()
plt.show()
WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.

WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\backend.py:1398: The name tf.executing_eagerly_outside_functions is deprecated. Please use tf.compat.v1.executing_eagerly_outside_functions instead.

WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\layers\normalization\batch_normalization.py:979: The name tf.nn.fused_batch_norm is deprecated. Please use tf.compat.v1.nn.fused_batch_norm instead.

Training Age Model
Epoch 1/100
WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\utils\tf_utils.py:492: The name tf.ragged.RaggedTensorValue is deprecated. Please use tf.compat.v1.ragged.RaggedTensorValue instead.

WARNING:tensorflow:From C:\ProgramData\anaconda3\Lib\site-packages\keras\src\engine\base_layer_utils.py:384: The name tf.executing_eagerly_outside_functions is deprecated. Please use tf.compat.v1.executing_eagerly_outside_functions instead.

565/565 [==============================] - ETA: 0s - loss: 9.1021 - mae: 9.1021
Epoch 1: val_loss improved from inf to 13.55556, saving model to age_model_weights.h5
565/565 [==============================] - 727s 1s/step - loss: 9.1021 - mae: 9.1021 - val_loss: 13.5556 - val_mae: 13.5556
Epoch 2/100
565/565 [==============================] - ETA: 0s - loss: 5.8263 - mae: 5.8263
Epoch 2: val_loss improved from 13.55556 to 6.72425, saving model to age_model_weights.h5
565/565 [==============================] - 708s 1s/step - loss: 5.8263 - mae: 5.8263 - val_loss: 6.7243 - val_mae: 6.7243
Epoch 3/100
565/565 [==============================] - ETA: 0s - loss: 4.9837 - mae: 4.9837
Epoch 3: val_loss improved from 6.72425 to 5.97589, saving model to age_model_weights.h5
565/565 [==============================] - 709s 1s/step - loss: 4.9837 - mae: 4.9837 - val_loss: 5.9759 - val_mae: 5.9759
Epoch 4/100
565/565 [==============================] - ETA: 0s - loss: 4.2513 - mae: 4.2513
Epoch 4: val_loss improved from 5.97589 to 5.76154, saving model to age_model_weights.h5
565/565 [==============================] - 713s 1s/step - loss: 4.2513 - mae: 4.2513 - val_loss: 5.7615 - val_mae: 5.7615
Epoch 5/100
565/565 [==============================] - ETA: 0s - loss: 3.7080 - mae: 3.7080
Epoch 5: val_loss improved from 5.76154 to 5.65393, saving model to age_model_weights.h5
565/565 [==============================] - 697s 1s/step - loss: 3.7080 - mae: 3.7080 - val_loss: 5.6539 - val_mae: 5.6539
Epoch 6/100
565/565 [==============================] - ETA: 0s - loss: 3.2931 - mae: 3.2931
Epoch 6: val_loss did not improve from 5.65393
565/565 [==============================] - 696s 1s/step - loss: 3.2931 - mae: 3.2931 - val_loss: 5.6570 - val_mae: 5.6570
Epoch 7/100
565/565 [==============================] - ETA: 0s - loss: 3.0069 - mae: 3.0069
Epoch 7: val_loss improved from 5.65393 to 5.38913, saving model to age_model_weights.h5
565/565 [==============================] - 680s 1s/step - loss: 3.0069 - mae: 3.0069 - val_loss: 5.3891 - val_mae: 5.3891
Epoch 8/100
565/565 [==============================] - ETA: 0s - loss: 2.8060 - mae: 2.8060
Epoch 8: val_loss did not improve from 5.38913
565/565 [==============================] - 654s 1s/step - loss: 2.8060 - mae: 2.8060 - val_loss: 5.5301 - val_mae: 5.5301
Epoch 9/100
565/565 [==============================] - ETA: 0s - loss: 2.5405 - mae: 2.5405
Epoch 9: val_loss did not improve from 5.38913
565/565 [==============================] - 654s 1s/step - loss: 2.5405 - mae: 2.5405 - val_loss: 5.4949 - val_mae: 5.4949
Epoch 10/100
565/565 [==============================] - ETA: 0s - loss: 2.4118 - mae: 2.4118
Epoch 10: val_loss did not improve from 5.38913
565/565 [==============================] - 657s 1s/step - loss: 2.4118 - mae: 2.4118 - val_loss: 5.5589 - val_mae: 5.5589
Epoch 11/100
565/565 [==============================] - ETA: 0s - loss: 2.3166 - mae: 2.3166
Epoch 11: val_loss did not improve from 5.38913
565/565 [==============================] - 655s 1s/step - loss: 2.3166 - mae: 2.3166 - val_loss: 5.5551 - val_mae: 5.5551
Epoch 12/100
565/565 [==============================] - ETA: 0s - loss: 2.2050 - mae: 2.2050
Epoch 12: val_loss improved from 5.38913 to 5.21495, saving model to age_model_weights.h5
565/565 [==============================] - 654s 1s/step - loss: 2.2050 - mae: 2.2050 - val_loss: 5.2150 - val_mae: 5.2150
Epoch 13/100
565/565 [==============================] - ETA: 0s - loss: 2.1182 - mae: 2.1182
Epoch 13: val_loss did not improve from 5.21495
565/565 [==============================] - 653s 1s/step - loss: 2.1182 - mae: 2.1182 - val_loss: 5.4208 - val_mae: 5.4208
Epoch 14/100
565/565 [==============================] - ETA: 0s - loss: 2.0366 - mae: 2.0366
Epoch 14: val_loss did not improve from 5.21495
565/565 [==============================] - 654s 1s/step - loss: 2.0366 - mae: 2.0366 - val_loss: 5.3071 - val_mae: 5.3071
Epoch 15/100
565/565 [==============================] - ETA: 0s - loss: 1.9743 - mae: 1.9743
Epoch 15: val_loss did not improve from 5.21495
565/565 [==============================] - 656s 1s/step - loss: 1.9743 - mae: 1.9743 - val_loss: 5.6122 - val_mae: 5.6122
Epoch 16/100
565/565 [==============================] - ETA: 0s - loss: 1.9131 - mae: 1.9131
Epoch 16: val_loss did not improve from 5.21495
565/565 [==============================] - 654s 1s/step - loss: 1.9131 - mae: 1.9131 - val_loss: 5.2598 - val_mae: 5.2598
Epoch 17/100
565/565 [==============================] - ETA: 0s - loss: 1.8557 - mae: 1.8557
Epoch 17: val_loss did not improve from 5.21495
565/565 [==============================] - 656s 1s/step - loss: 1.8557 - mae: 1.8557 - val_loss: 5.2917 - val_mae: 5.2917
Epoch 18/100
565/565 [==============================] - ETA: 0s - loss: 1.8001 - mae: 1.8001
Epoch 18: val_loss improved from 5.21495 to 5.18326, saving model to age_model_weights.h5
565/565 [==============================] - 654s 1s/step - loss: 1.8001 - mae: 1.8001 - val_loss: 5.1833 - val_mae: 5.1833
Epoch 19/100
565/565 [==============================] - ETA: 0s - loss: 1.7865 - mae: 1.7865
Epoch 19: val_loss improved from 5.18326 to 5.13139, saving model to age_model_weights.h5
565/565 [==============================] - 650s 1s/step - loss: 1.7865 - mae: 1.7865 - val_loss: 5.1314 - val_mae: 5.1314
Epoch 20/100
565/565 [==============================] - ETA: 0s - loss: 1.7104 - mae: 1.7104
Epoch 20: val_loss did not improve from 5.13139
565/565 [==============================] - 653s 1s/step - loss: 1.7104 - mae: 1.7104 - val_loss: 5.2586 - val_mae: 5.2586
Epoch 21/100
565/565 [==============================] - ETA: 0s - loss: 1.6712 - mae: 1.6712
Epoch 21: val_loss did not improve from 5.13139
565/565 [==============================] - 656s 1s/step - loss: 1.6712 - mae: 1.6712 - val_loss: 5.2644 - val_mae: 5.2644
Epoch 22/100
565/565 [==============================] - ETA: 0s - loss: 1.6295 - mae: 1.6295
Epoch 22: val_loss did not improve from 5.13139
565/565 [==============================] - 652s 1s/step - loss: 1.6295 - mae: 1.6295 - val_loss: 5.1994 - val_mae: 5.1994
Epoch 23/100
565/565 [==============================] - ETA: 0s - loss: 1.6118 - mae: 1.6118
Epoch 23: val_loss did not improve from 5.13139
565/565 [==============================] - 650s 1s/step - loss: 1.6118 - mae: 1.6118 - val_loss: 5.2255 - val_mae: 5.2255
Epoch 24/100
565/565 [==============================] - ETA: 0s - loss: 1.5953 - mae: 1.5953
Epoch 24: val_loss did not improve from 5.13139
565/565 [==============================] - 652s 1s/step - loss: 1.5953 - mae: 1.5953 - val_loss: 5.2195 - val_mae: 5.2195
Epoch 25/100
565/565 [==============================] - ETA: 0s - loss: 1.5526 - mae: 1.5526
Epoch 25: val_loss did not improve from 5.13139
565/565 [==============================] - 653s 1s/step - loss: 1.5526 - mae: 1.5526 - val_loss: 5.2433 - val_mae: 5.2433
Epoch 26/100
565/565 [==============================] - ETA: 0s - loss: 1.5086 - mae: 1.5086
Epoch 26: val_loss improved from 5.13139 to 5.11697, saving model to age_model_weights.h5
565/565 [==============================] - 655s 1s/step - loss: 1.5086 - mae: 1.5086 - val_loss: 5.1170 - val_mae: 5.1170
Epoch 27/100
565/565 [==============================] - ETA: 0s - loss: 1.4581 - mae: 1.4581
Epoch 27: val_loss did not improve from 5.11697
565/565 [==============================] - 654s 1s/step - loss: 1.4581 - mae: 1.4581 - val_loss: 5.3278 - val_mae: 5.3278
Epoch 28/100
565/565 [==============================] - ETA: 0s - loss: 1.4632 - mae: 1.4632
Epoch 28: val_loss did not improve from 5.11697
565/565 [==============================] - 654s 1s/step - loss: 1.4632 - mae: 1.4632 - val_loss: 5.2567 - val_mae: 5.2567
Epoch 29/100
565/565 [==============================] - ETA: 0s - loss: 1.4632 - mae: 1.4632
Epoch 29: val_loss did not improve from 5.11697
565/565 [==============================] - 653s 1s/step - loss: 1.4632 - mae: 1.4632 - val_loss: 5.2700 - val_mae: 5.2700
Epoch 30/100
565/565 [==============================] - ETA: 0s - loss: 1.4466 - mae: 1.4466
Epoch 30: val_loss did not improve from 5.11697
565/565 [==============================] - 652s 1s/step - loss: 1.4466 - mae: 1.4466 - val_loss: 5.4616 - val_mae: 5.4616
Epoch 31/100
565/565 [==============================] - ETA: 0s - loss: 1.3756 - mae: 1.3756
Epoch 31: val_loss did not improve from 5.11697
565/565 [==============================] - 656s 1s/step - loss: 1.3756 - mae: 1.3756 - val_loss: 5.1913 - val_mae: 5.1913
Epoch 32/100
565/565 [==============================] - ETA: 0s - loss: 1.3394 - mae: 1.3394
Epoch 32: val_loss did not improve from 5.11697
565/565 [==============================] - 655s 1s/step - loss: 1.3394 - mae: 1.3394 - val_loss: 5.1424 - val_mae: 5.1424
Epoch 33/100
565/565 [==============================] - ETA: 0s - loss: 1.3476 - mae: 1.3476
Epoch 33: val_loss did not improve from 5.11697
565/565 [==============================] - 653s 1s/step - loss: 1.3476 - mae: 1.3476 - val_loss: 5.2438 - val_mae: 5.2438
Epoch 34/100
565/565 [==============================] - ETA: 0s - loss: 1.2936 - mae: 1.2936
Epoch 34: val_loss improved from 5.11697 to 5.11448, saving model to age_model_weights.h5
565/565 [==============================] - 659s 1s/step - loss: 1.2936 - mae: 1.2936 - val_loss: 5.1145 - val_mae: 5.1145
Epoch 35/100
565/565 [==============================] - ETA: 0s - loss: 1.2881 - mae: 1.2881
Epoch 35: val_loss did not improve from 5.11448
565/565 [==============================] - 657s 1s/step - loss: 1.2881 - mae: 1.2881 - val_loss: 5.1236 - val_mae: 5.1236
Epoch 36/100
565/565 [==============================] - ETA: 0s - loss: 1.2766 - mae: 1.2766
Epoch 36: val_loss did not improve from 5.11448
565/565 [==============================] - 655s 1s/step - loss: 1.2766 - mae: 1.2766 - val_loss: 5.1492 - val_mae: 5.1492
Epoch 37/100
565/565 [==============================] - ETA: 0s - loss: 1.2767 - mae: 1.2767
Epoch 37: val_loss did not improve from 5.11448
565/565 [==============================] - 657s 1s/step - loss: 1.2767 - mae: 1.2767 - val_loss: 5.1414 - val_mae: 5.1414
Epoch 38/100
565/565 [==============================] - ETA: 0s - loss: 1.2715 - mae: 1.2715
Epoch 38: val_loss did not improve from 5.11448
565/565 [==============================] - 657s 1s/step - loss: 1.2715 - mae: 1.2715 - val_loss: 5.5241 - val_mae: 5.5241
Epoch 39/100
565/565 [==============================] - ETA: 0s - loss: 1.2431 - mae: 1.2431
Epoch 39: val_loss did not improve from 5.11448
565/565 [==============================] - 654s 1s/step - loss: 1.2431 - mae: 1.2431 - val_loss: 5.2399 - val_mae: 5.2399
Epoch 40/100
565/565 [==============================] - ETA: 0s - loss: 1.2368 - mae: 1.2368
Epoch 40: val_loss did not improve from 5.11448
565/565 [==============================] - 656s 1s/step - loss: 1.2368 - mae: 1.2368 - val_loss: 5.2310 - val_mae: 5.2310
Epoch 41/100
565/565 [==============================] - ETA: 0s - loss: 1.1613 - mae: 1.1613
Epoch 41: val_loss did not improve from 5.11448
565/565 [==============================] - 724s 1s/step - loss: 1.1613 - mae: 1.1613 - val_loss: 5.1684 - val_mae: 5.1684
Epoch 42/100
565/565 [==============================] - ETA: 0s - loss: 1.1652 - mae: 1.1652
Epoch 42: val_loss did not improve from 5.11448
565/565 [==============================] - 768s 1s/step - loss: 1.1652 - mae: 1.1652 - val_loss: 5.2017 - val_mae: 5.2017
Epoch 43/100
565/565 [==============================] - ETA: 0s - loss: 1.1631 - mae: 1.1631
Epoch 43: val_loss did not improve from 5.11448
565/565 [==============================] - 733s 1s/step - loss: 1.1631 - mae: 1.1631 - val_loss: 5.1220 - val_mae: 5.1220
Epoch 44/100
565/565 [==============================] - ETA: 0s - loss: 1.1408 - mae: 1.1408
Epoch 44: val_loss did not improve from 5.11448
565/565 [==============================] - 729s 1s/step - loss: 1.1408 - mae: 1.1408 - val_loss: 5.2422 - val_mae: 5.2422
Epoch 44: early stopping
Age Model training stopped at epoch: 44
Training Gender Model
Epoch 1/50
565/565 [==============================] - ETA: 0s - loss: 0.2529 - accuracy: 0.8923
Epoch 1: val_loss improved from inf to 0.20330, saving model to gender_model_weights.h5
565/565 [==============================] - 691s 1s/step - loss: 0.2529 - accuracy: 0.8923 - val_loss: 0.2033 - val_accuracy: 0.9195
Epoch 2/50
565/565 [==============================] - ETA: 0s - loss: 0.0994 - accuracy: 0.9650
Epoch 2: val_loss did not improve from 0.20330
565/565 [==============================] - 652s 1s/step - loss: 0.0994 - accuracy: 0.9650 - val_loss: 0.2052 - val_accuracy: 0.9205
Epoch 3/50
565/565 [==============================] - ETA: 0s - loss: 0.0372 - accuracy: 0.9888
Epoch 3: val_loss did not improve from 0.20330
565/565 [==============================] - 656s 1s/step - loss: 0.0372 - accuracy: 0.9888 - val_loss: 0.2738 - val_accuracy: 0.9235
Epoch 4/50
565/565 [==============================] - ETA: 0s - loss: 0.0226 - accuracy: 0.9910
Epoch 4: val_loss did not improve from 0.20330
565/565 [==============================] - 657s 1s/step - loss: 0.0226 - accuracy: 0.9910 - val_loss: 0.3163 - val_accuracy: 0.9245
Epoch 5/50
565/565 [==============================] - ETA: 0s - loss: 0.0179 - accuracy: 0.9905
Epoch 5: val_loss did not improve from 0.20330
565/565 [==============================] - 657s 1s/step - loss: 0.0179 - accuracy: 0.9905 - val_loss: 0.4067 - val_accuracy: 0.9136
Epoch 6/50
565/565 [==============================] - ETA: 0s - loss: 0.0166 - accuracy: 0.9899
Epoch 6: val_loss did not improve from 0.20330
565/565 [==============================] - 654s 1s/step - loss: 0.0166 - accuracy: 0.9899 - val_loss: 0.3826 - val_accuracy: 0.9142
Epoch 7/50
565/565 [==============================] - ETA: 0s - loss: -0.0075 - accuracy: 0.9930
Epoch 7: val_loss did not improve from 0.20330
565/565 [==============================] - 654s 1s/step - loss: -0.0075 - accuracy: 0.9930 - val_loss: 0.3724 - val_accuracy: 0.9223
Epoch 8/50
565/565 [==============================] - ETA: 0s - loss: -0.0105 - accuracy: 0.9920
Epoch 8: val_loss did not improve from 0.20330
565/565 [==============================] - 655s 1s/step - loss: -0.0105 - accuracy: 0.9920 - val_loss: 48.8834 - val_accuracy: 0.5467
Epoch 9/50
565/565 [==============================] - ETA: 0s - loss: 0.0080 - accuracy: 0.9881
Epoch 9: val_loss did not improve from 0.20330
565/565 [==============================] - 663s 1s/step - loss: 0.0080 - accuracy: 0.9881 - val_loss: 0.4285 - val_accuracy: 0.9230
Epoch 10/50
565/565 [==============================] - ETA: 0s - loss: -0.0514 - accuracy: 0.9954
Epoch 10: val_loss did not improve from 0.20330
565/565 [==============================] - 773s 1s/step - loss: -0.0514 - accuracy: 0.9954 - val_loss: 0.7789 - val_accuracy: 0.9293
Epoch 11/50
565/565 [==============================] - ETA: 0s - loss: -0.0671 - accuracy: 0.9936
Epoch 11: val_loss did not improve from 0.20330
565/565 [==============================] - 793s 1s/step - loss: -0.0671 - accuracy: 0.9936 - val_loss: 0.4882 - val_accuracy: 0.9124
Epoch 11: early stopping
Gender Model training stopped at epoch: 11
In [2]:
# Eğitim ve doğrulama MAE grafikleri için Age Model
plt.figure(figsize=(12, 8))

plt.subplot(2, 2, 1)
plt.plot(history_age.history['loss'], label='Training Loss')
plt.plot(history_age.history['val_loss'], label='Validation Loss')
plt.title('Age Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.subplot(2, 2, 2)
plt.plot(history_age.history['mae'], label='Training MAE')
plt.plot(history_age.history['val_mae'], label='Validation MAE')
plt.title('Age Model Training and Validation MAE')
plt.xlabel('Epoch')
plt.ylabel('MAE')
plt.legend()

# Eğitim ve doğrulama kaybı grafikleri için Gender Model
plt.subplot(2, 2, 3)
plt.plot(history_gender.history['loss'], label='Training Loss')
plt.plot(history_gender.history['val_loss'], label='Validation Loss')
plt.title('Gender Model Training and Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()

plt.subplot(2, 2, 4)
plt.plot(history_gender.history['accuracy'], label='Training Accuracy')
plt.plot(history_gender.history['val_accuracy'], label='Validation Accuracy')
plt.title('Gender Model Training and Validation Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()

plt.tight_layout()
plt.show()
In [37]:
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, mean_absolute_error
import seaborn as sns

# Her yaş için kişi sayısını hesaplama
age_counts = {}
for age in ages_np:
    if age in age_counts:
        age_counts[age] += 1
    else:
        age_counts[age] = 1

# Yaşlara göre dağılımı sıralı bir şekilde almak
sorted_ages = sorted(age_counts.keys())
counts = [age_counts[age] for age in sorted_ages]

# Yaş Dağılım Grafiği
plt.figure(figsize=(15, 5))
plt.plot(sorted_ages, counts, marker='o')
plt.xlabel('Ages')
plt.ylabel('Number of Individuals')
plt.title('Age Distribution in the Dataset')
plt.grid(True)
plt.show()

# Yaş ve Cinsiyet Doğruluk Değerlerini Çiz (Sadece Cinsiyet İçin)
plt.figure(figsize=(6, 6))
gender_ranges = list(gender_accuracies.keys())
accuracies_gender = list(gender_accuracies.values())
x_ticks = np.arange(1, 121, 5)
plt.barh(gender_ranges, accuracies_gender, color='salmon')
plt.xticks(x_ticks)
plt.xlim(0, 100)
plt.xlabel('Accuracy (%)')
plt.ylabel('Age Range')
plt.title('Gender Prediction Accuracy')
plt.show()

# Cinsiyet Modeli İçin Sınıflandırma Raporu
gender_model.load_weights('C:/Users/kasim.sahin/gender_model_weights.h5')
y_pred_gender = gender_model.predict(X_test)
y_pred_gender = (y_pred_gender > 0.5).astype(int)
print("Gender Classification Report:")
print(classification_report(Y_gender_test, y_pred_gender))

# Yaş Tahmini İçin MAE
age_model.load_weights('C:/Users/kasim.sahin/age_model_weights.h5')
y_pred_age = age_model.predict(X_test)
mae = mean_absolute_error(Y_age_test, y_pred_age)
print("Mean Absolute Error (MAE) for Age Prediction:", mae)

# Veri Setindeki Yaş Dağılımı
plt.figure(figsize=(10, 4))
sns.histplot(Y_age_test, bins=20, color='blue', label='Actual Age', kde=True)
sns.histplot(y_pred_age, bins=20, color='green', label='Predicted Age', kde=True)
for age in range(0, 120, 10):
    plt.axvline(x=age, color='green', linestyle='--', linewidth=1, label=f'{age} years')
plt.title('Age Distribution in the Data Set')
plt.xlabel('Age')
plt.legend(loc='upper right')
plt.show()

# Yaş Tahminlerini Karşılaştırma Grafiği
fig, ax = plt.subplots()
ax.scatter(Y_age_test, y_pred_age.flatten())  # Adjusted with y_pred_age.flatten()
ax.plot([Y_age_test.min(), Y_age_test.max()], [Y_age_test.min(), Y_age_test.max()], 'k--', lw=4)
ax.set_xlabel('Actual Age')
ax.set_ylabel('Predicted Age')
plt.title('Actual vs Predicted Age')
plt.show()
189/189 [==============================] - 98s 516ms/step
Gender Classification Report:
              precision    recall  f1-score   support

           0       0.93      0.92      0.92      3173
           1       0.91      0.92      0.92      2854

    accuracy                           0.92      6027
   macro avg       0.92      0.92      0.92      6027
weighted avg       0.92      0.92      0.92      6027

189/189 [==============================] - 97s 515ms/step
Mean Absolute Error (MAE) for Age Prediction: 5.11447659692144
In [35]:
def calculate_accuracy_within_3_years(y_true, y_pred):
    correct = 0
    total = len(y_true)

    for actual_age, predicted_age in zip(y_true, y_pred):
        lower_bound = predicted_age - 3
        upper_bound = predicted_age + 3
        if lower_bound <= actual_age <= upper_bound:
            correct += 1

    accuracy = (correct / total) * 100
    return accuracy

# Age Model tahminleri
predicted_ages = age_model.predict(X_test).flatten()

# Tahminlerin doğruluğunu hesapla
accuracy_within_3_years = calculate_accuracy_within_3_years(Y_age_test, predicted_ages)

# Doğruluk oranını bas
print(f"Accuracy within 3 years: {accuracy_within_3_years}%")

# Doğruluk oranını gösteren grafik
plt.figure(figsize=(6, 4))
plt.bar(['Accuracy'], [accuracy_within_3_years])
plt.ylabel('Accuracy (%)')
plt.title('Prediction Accuracy Within 3 Years Age Range')
plt.ylim(0, 100)
plt.show()
189/189 [==============================] - 99s 524ms/step
Accuracy within 3 years: 46.52397544383607%
In [22]:
def calculate_accuracy_within_3_years_per_age_group(y_true, y_pred, age_groups):
    # Her yaş grubu için doğruluk oranlarını saklayacak sözlük
    accuracy_per_group = {group: {'correct': 0, 'total': 0} for group in age_groups}

    for actual_age, predicted_age in zip(y_true, y_pred):
        # Hangi yaş grubuna ait olduğunu bul
        age_group = min([group for group in age_groups if actual_age in group])

        # 3 yıllık aralıkta doğru mu kontrol et
        lower_bound = predicted_age - 3
        upper_bound = predicted_age + 3
        if lower_bound <= actual_age <= upper_bound:
            accuracy_per_group[age_group]['correct'] += 1
        accuracy_per_group[age_group]['total'] += 1

    # Her yaş grubu için yüzde doğruluk hesapla, 0'a bölme hatasını önle
    accuracy_percentages = {}
    for group, values in accuracy_per_group.items():
        if values['total'] > 0:
            accuracy = (values['correct'] / values['total']) * 100
        else:
            accuracy = 'N/A'  # Veri yok
        accuracy_percentages[group] = accuracy

    return accuracy_percentages

# Yaş gruplarını tanımla (0-120 arası 5'er yıllık dilimler)
age_groups = [range(i, i + 5) for i in range(1, 121, 5)]

# Age Model tahminleri
predicted_ages = age_model.predict(X_test).flatten()

# Her yaş grubu için doğruluk oranını hesapla
accuracy_per_age_group = calculate_accuracy_within_3_years_per_age_group(Y_age_test, predicted_ages, age_groups)

# Sonuçları bas
for age_group, accuracy in accuracy_per_age_group.items():
    print(f"Age group {min(age_group)}-{max(age_group)}: {accuracy} accuracy")

# Sonuçları grafikte göster (N/A durumları hariç tut)
plt.figure(figsize=(16, 8))
plt.bar(range(len(accuracy_per_age_group)), [acc if isinstance(acc, float) else 0 for acc in accuracy_per_age_group.values()], align='center')
plt.xticks(range(len(accuracy_per_age_group)), [f"{min(group)}-{max(group)}" for group in age_groups])
plt.xlabel('Age Groups')
plt.ylabel('Accuracy (%)')
plt.title('Prediction Accuracy Within 3 Years for Each Age Group')
plt.show()
189/189 [==============================] - 101s 535ms/step
Age group 1-5: 90.20771513353115 accuracy
Age group 6-10: 55.15695067264574 accuracy
Age group 11-15: 40.23668639053255 accuracy
Age group 16-20: 26.666666666666668 accuracy
Age group 21-25: 53.85714285714286 accuracy
Age group 26-30: 62.55077173030057 accuracy
Age group 31-35: 35.738255033557046 accuracy
Age group 36-40: 25.82781456953642 accuracy
Age group 41-45: 25.589225589225588 accuracy
Age group 46-50: 29.249011857707508 accuracy
Age group 51-55: 33.53846153846154 accuracy
Age group 56-60: 29.23728813559322 accuracy
Age group 61-65: 26.666666666666668 accuracy
Age group 66-70: 27.906976744186046 accuracy
Age group 71-75: 17.073170731707318 accuracy
Age group 76-80: 13.750000000000002 accuracy
Age group 81-85: 28.767123287671232 accuracy
Age group 86-90: 3.7735849056603774 accuracy
Age group 91-95: 0.0 accuracy
Age group 96-100: 0.0 accuracy
Age group 101-105: 0.0 accuracy
Age group 106-110: 0.0 accuracy
Age group 111-115: N/A accuracy
Age group 116-120: 0.0 accuracy
In [49]:
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
from sklearn.model_selection import train_test_split

# Set the path to the dataset
data_folder = "C:/yas_tahmini/UTKFaceee"

# Load and process the data
files = os.listdir(data_folder)
ages = []
genders = []
images = []

for file in files:
    parts = file.split('_')
    if len(parts) < 3 or not parts[0].isdigit() or not parts[1].isdigit():
        continue

    age, gender = map(int, parts[:2])
    ages.append(age)
    genders.append(gender)

ages_np = np.array(ages, dtype=np.float32)
genders_np = np.array(genders, dtype=np.float32)

# Function to process and return a single image
def process_image(file):
    full_path = os.path.join(data_folder, file)
    image = cv2.imread(full_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (224, 224))
    image = image.astype(np.float32) / 255
    return image

# Test Specific Images Function
def test_specific_images(indices, age_model, gender_model):
    for index in indices:
        if 0 <= index < len(files):
            file = files[index]
            actual_age, actual_gender = ages_np[index], genders_np[index]
            actual_age = int(actual_age)  # Yaşı tam sayıya dönüştür
            actual_gender_str = 'Female' if actual_gender == 1 else 'Male'

            image = process_image(file)
            plt.imshow(image)
            plt.title(f"Filename: {file}")
            plt.show()

            age_pred = age_model.predict(np.array([image]))
            gender_pred = gender_model.predict(np.array([image]))

            predicted_age = int(np.round(age_pred[0]))
            predicted_gender = 'Female' if int(np.round(gender_pred[0])) == 1 else 'Male'

            print(f"Actual Age: {actual_age}, Actual Gender: {actual_gender_str}")
            print(f"Predicted Age: {predicted_age}, Predicted Gender: {predicted_gender}")
        else:
            print(f"Index {index} is out of range. Valid range is 0 to {len(files) - 1}")


# Load your models (age_model and gender_model)
# Make sure to load or define your models here

# Test the models with specific indices
specific_indices = [52, 615, 650, 549, 4961, 2537, 2902, 278, 1451, 3001, 1904, 181, 5472]
test_specific_images(specific_indices, age_model, gender_model)
1/1 [==============================] - 0s 153ms/step
1/1 [==============================] - 0s 146ms/step
Actual Age: 10, Actual Gender: Male
Predicted Age: 10, Predicted Gender: Male
1/1 [==============================] - 0s 127ms/step
1/1 [==============================] - 0s 126ms/step
Actual Age: 14, Actual Gender: Female
Predicted Age: 14, Predicted Gender: Female
1/1 [==============================] - 0s 141ms/step
1/1 [==============================] - 0s 131ms/step
Actual Age: 15, Actual Gender: Male
Predicted Age: 24, Predicted Gender: Male
1/1 [==============================] - 0s 126ms/step
1/1 [==============================] - 0s 153ms/step
Actual Age: 14, Actual Gender: Male
Predicted Age: 16, Predicted Gender: Male
1/1 [==============================] - 0s 124ms/step
1/1 [==============================] - 0s 145ms/step
Actual Age: 24, Actual Gender: Female
Predicted Age: 23, Predicted Gender: Female
1/1 [==============================] - 0s 128ms/step
1/1 [==============================] - 0s 159ms/step
Actual Age: 1, Actual Gender: Female
Predicted Age: 1, Predicted Gender: Female
1/1 [==============================] - 0s 128ms/step
1/1 [==============================] - 0s 176ms/step
Actual Age: 20, Actual Gender: Male
Predicted Age: 22, Predicted Gender: Male
1/1 [==============================] - 0s 146ms/step
1/1 [==============================] - 0s 152ms/step
Actual Age: 12, Actual Gender: Male
Predicted Age: 14, Predicted Gender: Male
1/1 [==============================] - 0s 156ms/step
1/1 [==============================] - 0s 132ms/step
Actual Age: 18, Actual Gender: Female
Predicted Age: 13, Predicted Gender: Female
1/1 [==============================] - 0s 130ms/step
1/1 [==============================] - 0s 142ms/step
Actual Age: 20, Actual Gender: Female
Predicted Age: 19, Predicted Gender: Female
1/1 [==============================] - 0s 144ms/step
1/1 [==============================] - 0s 139ms/step
Actual Age: 1, Actual Gender: Male
Predicted Age: 1, Predicted Gender: Female
1/1 [==============================] - 0s 139ms/step
1/1 [==============================] - 0s 134ms/step
Actual Age: 110, Actual Gender: Female
Predicted Age: 117, Predicted Gender: Female
1/1 [==============================] - 0s 158ms/step
1/1 [==============================] - 0s 149ms/step
Actual Age: 25, Actual Gender: Male
Predicted Age: 24, Predicted Gender: Male
In [16]:
import cv2
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.models import Model
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Input, GlobalAveragePooling2D, Dense

# Age ve Gender Model'lerini yeniden oluşturun ve ağırlıkları yükleyin

# Age Model
base_model_age = ResNet50(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))
x_age = GlobalAveragePooling2D()(base_model_age.output)
x_age = Dense(64, activation='relu')(x_age)
output_age = Dense(1, activation='relu', name='age_output')(x_age)
age_model = Model(inputs=base_model_age.input, outputs=output_age)
age_model.load_weights('age_model_weights.h5')  # Yolun doğru olduğundan emin olun

# Gender Model
base_model_gender = ResNet50(weights='imagenet', include_top=False, input_tensor=Input(shape=(224, 224, 3)))
x_gender = GlobalAveragePooling2D()(base_model_gender.output)
x_gender = Dense(64, activation='relu')(x_gender)
output_gender = Dense(1, activation='sigmoid', name='gender_output')(x_gender)
gender_model = Model(inputs=base_model_gender.input, outputs=output_gender)
gender_model.load_weights('gender_model_weights.h5')  # Yolun doğru olduğundan emin olun

# Resim tahmini fonksiyonunu tanımla
def external_test_image(image_path, age_model, gender_model):
    # Resmi yükle ve boyutlandır
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (224, 224))

    # Resmi göster
    plt.imshow(image)
    plt.title(f"Test Image: {image_path}")
    plt.show()

    # Normalize et ve tahmin yap
    image = np.array(image) / 255.0
    age_pred = age_model.predict(np.array([image]))
    gender_pred = gender_model.predict(np.array([image]))

    # Tahminleri al ve yazdır
    predicted_age = int(np.round(age_pred[0][0]))
    predicted_gender = 'Female' if int(np.round(gender_pred[0][0])) == 1 else 'Male'

    print(f"Predicted Age: {predicted_age}, Predicted Gender: {predicted_gender}")

# Test resimleri
test_images = [
    'C:/yas_tahmini/kasim.jpg',
    'C:/yas_tahmini/ali_ihsan.jpg',
    'C:/yas_tahmini/kasim.jpg',
    'C:/yas_tahmini/ali_ihsan.jpg',
    'C:/yas_tahmini/serdar.jpg',
    'C:/yas_tahmini/kasim2.jpg',
    'C:/yas_tahmini/kasim3.jpg',
    'C:/yas_tahmini/kasim4.jpg',
    'C:/yas_tahmini/kasim5.jpg',
    'C:/yas_tahmini/kasim6.jpg',
    'C:/yas_tahmini/ali_ihsan2.jpg',
    'C:/yas_tahmini/fuat.jpg',
    'C:/yas_tahmini/osman.jpg',
    'C:/yas_tahmini/ozge.jpg',
    'C:/yas_tahmini/ozgur.jpg',
    'C:/yas_tahmini/emre_sumer.jpg',
    'C:/yas_tahmini/didem_olcer.jpg',
    'C:/yas_tahmini/mustafa_sert.jpg',
    'C:/yas_tahmini/merve.jpg',
    'C:/yas_tahmini/ali_ihsan3.jpeg',
]

# Her resim için tahmin yap
for img_path in test_images:
    external_test_image(img_path, age_model, gender_model)
1/1 [==============================] - 1s 1s/step
1/1 [==============================] - 1s 1s/step
Predicted Age: 27, Predicted Gender: Male
1/1 [==============================] - 0s 169ms/step
1/1 [==============================] - 0s 172ms/step
Predicted Age: 48, Predicted Gender: Male
1/1 [==============================] - 0s 177ms/step
1/1 [==============================] - 0s 194ms/step
Predicted Age: 27, Predicted Gender: Male
1/1 [==============================] - 0s 181ms/step
1/1 [==============================] - 0s 159ms/step
Predicted Age: 48, Predicted Gender: Male
1/1 [==============================] - 0s 140ms/step
1/1 [==============================] - 0s 143ms/step
Predicted Age: 38, Predicted Gender: Male
1/1 [==============================] - 0s 164ms/step
1/1 [==============================] - 0s 165ms/step
Predicted Age: 30, Predicted Gender: Male
1/1 [==============================] - 0s 149ms/step
1/1 [==============================] - 0s 166ms/step
Predicted Age: 34, Predicted Gender: Male
1/1 [==============================] - 0s 175ms/step
1/1 [==============================] - 0s 186ms/step
Predicted Age: 44, Predicted Gender: Male
1/1 [==============================] - 0s 146ms/step
1/1 [==============================] - 0s 160ms/step
Predicted Age: 28, Predicted Gender: Male
1/1 [==============================] - 0s 171ms/step
1/1 [==============================] - 0s 201ms/step
Predicted Age: 24, Predicted Gender: Male
1/1 [==============================] - 0s 152ms/step
1/1 [==============================] - 0s 189ms/step
Predicted Age: 49, Predicted Gender: Male
1/1 [==============================] - 0s 138ms/step
1/1 [==============================] - 0s 171ms/step
Predicted Age: 40, Predicted Gender: Male
1/1 [==============================] - 0s 158ms/step
1/1 [==============================] - 0s 180ms/step
Predicted Age: 74, Predicted Gender: Male
1/1 [==============================] - 0s 177ms/step
1/1 [==============================] - 0s 162ms/step
Predicted Age: 31, Predicted Gender: Female
1/1 [==============================] - 0s 158ms/step
1/1 [==============================] - 0s 141ms/step
Predicted Age: 38, Predicted Gender: Male
1/1 [==============================] - 0s 156ms/step
1/1 [==============================] - 0s 160ms/step
Predicted Age: 53, Predicted Gender: Male
1/1 [==============================] - 0s 153ms/step
1/1 [==============================] - 0s 164ms/step
Predicted Age: 33, Predicted Gender: Female
1/1 [==============================] - 0s 169ms/step
1/1 [==============================] - 0s 143ms/step
Predicted Age: 51, Predicted Gender: Male
1/1 [==============================] - 0s 156ms/step
1/1 [==============================] - 0s 166ms/step
Predicted Age: 27, Predicted Gender: Female
1/1 [==============================] - 0s 128ms/step
1/1 [==============================] - 0s 158ms/step
Predicted Age: 54, Predicted Gender: Male
In [ ]: